package com.project.biz.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.biz.CmsOrderLogisticsBiz;
import com.project.entity.CmsOrderLogistics;
import com.project.mapper.CmsOrderLogisticsMapper;
import com.project.pojo.dto.ProductOrderLogisticsDTO;
import com.project.util.Kuaidi100Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 物流信息业务层接口实现类
 * @Author: zhuchi
 * @CreateDate: 2020/10/16 22:59
 * @Version: 1.0
 */
@Slf4j
@Service
public class CmsOrderLogisticsBizImpl extends ServiceImpl<CmsOrderLogisticsMapper, CmsOrderLogistics> implements CmsOrderLogisticsBiz {

    /**
     * 根据物流单号和物流公司编码获取物流信息,调用第三方查询
     * @param logisticsCompanyCode 物流公司编码
     * @param logisticsNumber 物流单号
     * @return
     */
    public List<ProductOrderLogisticsDTO> getOrderLogistics(String logisticsCompanyCode, String logisticsNumber){
        List<ProductOrderLogisticsDTO> productOrderLogisticsDTOS = new ArrayList<>();
        if (StringUtils.isNotBlank(logisticsCompanyCode) && StringUtils.isNotBlank(logisticsNumber)){
            //调用快递100接口查询物流信息
            JSONObject jsonObject = Kuaidi100Util.logisticsQuery(logisticsCompanyCode, logisticsNumber);

            if (jsonObject.containsKey("status") && jsonObject.getString("status").equals("200")){
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                if (null != jsonArray && jsonArray.size() > 0){
                    for (int i = 0, j = jsonArray.size(); i < j; i++){
                        JSONObject data = jsonArray.getJSONObject(i);
                        ProductOrderLogisticsDTO productOrderLogisticsDTO = new ProductOrderLogisticsDTO();
                        productOrderLogisticsDTO.setLogisticsInfo(data.getString("context"));
                        productOrderLogisticsDTO.setLogisticsTime(data.getString("ftime"));
                        productOrderLogisticsDTOS.add(productOrderLogisticsDTO);
                    }
                }
            }else {
                log.info("根据公司编码[{}]、物流单号[{}]查询物流信息失败,失败原因：{}", logisticsCompanyCode, logisticsNumber, jsonObject.getString("message"));
            }
        }
        return productOrderLogisticsDTOS;
    }

}
